//index.js
//获取应用实例
const app = getApp()
const http = require("../../config/api.js");
var user = require("../../utils/login.js")

Page({
  data: {
    bool: true,
    collection: true,
    api: "",
    imgUrl: "",
    id: '999',
    scrollLeft: 0,
    query: {
      userId: '',
      tagId: 7105,
      px: 2,
      project: "lyhad",
      cur: 1,
      pageSize: 10,
      province: '',
      area: '',
      type: "opera",
      sect: "",
      orderby: "online"
    },
    tabBar: [],
    indexList: [],
    isLogin: '',
    videoShow: true, // 播放按钮显示
    VIPTimenone: false, // 普通用户三分钟观看结束后显示
    videoindex: '', // 视频播放后的下标
    playurl: "",
    videoContext: "",
    myVideo: "",
    freeFlag: 1,// 0收费，1免费,
    index: 0,//播放的下标，
    codeArr: null, //专辑Code集合
    _index: null, //视频列表的下标
    log: {
      STOP_TIME: null,
      code: null,
      allTime: null,
      _index: null
    },
  },
  onLoad: function () {
    this.fnGetAlbumList();
    this.fnLocalSect();
  },
  onShow: function () {
    this.setData({
      ['query.userId']: app.globalData.userId,
      api: app.globalData.baseUrlApiTest,
      imgUrl: app.globalData.baseUrlImg,
    })
    // 每次进首页都要检测一下用户的vip状态，防止用户不是vip以后还可以播放
    user.getLogin().then(res => {
      this.setData({
        isVIP: wx.getStorageSync('isVIP')
      })
      if(this.data.isVIP) {
        for (var i in this.data.indexList) {
          this.data.indexList[i].flagShow = true
        }
      } else {
        // 因为检测到用户不是vip所以重新刷新内容，使用户无法播放
        this.fnGetAlbumList()
      }
    })
    // 访问日志
    let time = Math.round(new Date().getTime());
    let log = {
      //日志类型：unite.通用业务；visit.访问数据；click.点击数据；order.订购数据；error.错误日志
      logType: "visit",
      msg: JSON.stringify({
        mac: app.globalData.userId,
        page: "xcxindex",
        pageName: "梨园行首页",
        time: time,
        appVersionName: "小程序",
        item: 65,
        nodeCode: "001000",
        project: "lyhad",
        userId: app.globalData.memberId,
        deviceId: app.globalData.userId,
        uuid: user.getUuid(),
        pageLevel: "1"
      })
    }
    this.uniteLog(log)
  },
  //视频超出滚动立即停止播放
  onPageScroll: function (e) {
    this.createIntersectionObserver().relativeToViewport().observe("#" + "myVideo" + this.data._index, (res) => {
      let intersectionRatio = res.intersectionRatio;
      if (intersectionRatio <= 0.72 && intersectionRatio !== 0) {
        let STOP_TIME = this.data.log.STOP_TIME;
        if (STOP_TIME) {
          //有这个就执行
          this.addHistory(this.data.log.code, this.data.log.allTime, this.data.log._index, STOP_TIME);
        }
        this.setData({
          _index: null,
          ['log.STOP_TIME']: null
        })
      }
    })
  },
  /**
   * 动态改变scroll-left的值
   * */
  _handleScroll(selectedId) {
    var _this = this;
    var query = wx.createSelectorQuery(); //创建节点查询器
    query.select('#item-' + selectedId).boundingClientRect(); //选择id='#item-' + selectedId的节点，获取节点位置信息的查询请求
    query.select('#scroll-view').boundingClientRect(); //获取滑块的位置信息
    //获取滚动位置
    query.select('#scroll-view').scrollOffset(); //获取页面滑动位置的查询请求
    query.exec(function (res) {
      // console.log("res:",res)
      _this.setData({
        scrollLeft: res[2].scrollLeft + res[0].left + res[0].width / 2 - res[1].width / 2
      });
    });
  },
  onCouponItemClick(e) {
    let id = e.currentTarget.dataset.id;
    let code = e.currentTarget.dataset.code;
    this.setData({
      id: id,
      indexList: [],
      ['query.cur']: 1,
      ['query.sect']: code,
      bool: true
    })
    this._handleScroll(id);
    this.fnGetAlbumList();
  },
  // 获取推荐的数据
  fnGetAlbumList() {
    let id = this.data.id;
    let sect = this.data.query.sect;
    let bool = this.data.bool;
    if (!bool) {
      return false;
    };
    let data = {
      px: this.data.query.px,
      userId: this.data.query.userId,
      cur: this.data.query.cur,
      pageSize: this.data.query.pageSize,
    }
    if (id === '999') {
      data.tagId = this.data.query.tagId;
      data.project = this.data.query.project;
    } else {
      data.sect = sect.split(",");
      data.orderby = this.data.query.orderby;
    }
    let api_url = id === "999" ? "api_getTagAlbumList" : "api_getAlbumList"
    http.lhxRequest(api_url, data).then(res => {
      if (res.code === 10000000) {
        let indexList = this.data.indexList.length > 0 ? this.data.indexList : [];
        for (let i in res.pb.dataList) {
          res.pb.dataList[i].watch = 0 // watch等于0表示true，等于1表示false
          res.pb.dataList[i].VIPTimenone = 0
          res.pb.dataList[i].show = true;
          res.pb.dataList[i].flagShow = false;
          indexList.push(res.pb.dataList[i])
        }
        if (res.pb.dataList.length <= res.pb.pageSize && res.pb.cur === res.pb.totalPage) {
          this.setData({
            bool: false
          })
        }
        this.setData({
          indexList: indexList
        })
      }
    })
  },
  // 获取首页数据
  fnLocalSect() {
    let data = {
      area: this.data.query.area,
      project: this.data.query.project,
      province: this.data.query.province,
      type: this.data.query.type,
    };
    http.lhxRequest("api_localSect", data).then(res => {
      if (res.code === 10000000) {
        this.setData({
          tabBar: res.data
        })
      }
    })
  },
  // 添加收藏
  fnAddUserStore(e) {
    let code = e.currentTarget.dataset.code;
    let flag = e.currentTarget.dataset.flag;
    let idx = e.currentTarget.dataset.idx;
    let data = {
      userId: app.globalData.memberId || this.data.query.userId,
      resType: 5,
      project: this.data.query.project,
    }
    // 等于1的话点击是取消收藏 0 是添加收藏
    if (flag === 1) {
      data.range = 0;
      data.codes = [code];
      http.lhxRequest("api_delUserStore", data).then(res => {
        if (res.code === 10000000) {
          wx.showToast({
            title: '已取消收藏',
            icon: "none",
            duration: 3000,
          });
          this.setData({
            bool: true,
            ['indexList[' + idx + '].flag']: 0
          });
        }
      })
    } else {
      data.resCode =  code;
      data.item = 65;
      data.limitNum = 0; //不限制
      http.lhxRequest("api_addUserStore", data).then(res => {
        if (res.code === 10000000) {
          wx.showToast({
            title: '已添加到收藏，可在"我的"页面查看',
            icon: "none",
            duration: 3000,
          });
          this.setData({
            bool: true,
            ['indexList[' + idx + '].flag']: 1
          });
        }
      })
    }
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    let that = this;
    that.setData({
      indexList: [],
      ['query.cur']: 1,
      bool: true
    })
    that.fnGetAlbumList()
  },
  onReachBottom: function () {
    let that = this;
    let bool = that.data.bool;
    that.setData({
      ['query.cur']: that.data.query.cur += 1,
    })
    if (!bool) {
      wx.showToast({
        title: "没有更多数据",
        icon: "none",
        duration: 2000,
      });
    }
    that.fnGetAlbumList();
  },
  // 获取用户信息
  bindGetUserInfo: function (e) {
    console.log(e.detail)
    console.log(JSON.stringify(e.detail))
    console.log(e.detail.errMsg)
    console.log(e.detail.userInfo)
    console.log(e.detail.rawData)
  },
  gotwebView: function (e) {
    user.getUser(e.detail).then((res) => {
      if (wx.getStorageSync('isVIP')) {
        this.videoContext.play();
        this.data.indexList[this.data.videoindex].flagShow = false
        this.setData({
          indexList: this.data.indexList
        })
      } else {
        wx.navigateTo({
          url: '../webView/webView',
        })
      }
    }).catch(res => {
      wx.navigateTo({
        url: '../webView/webView',
      })
    })
  },
  //添加播放记录
  addHistory(code, aTime, index, stop) {
    let resCode = code || '';
    let allTime = aTime || 0;
    let timeStop = stop || null;
    let data = {
      userId: app.globalData.memberId || app.globalData.userId,
      resType: 1,
      resCode: resCode,
      allTime: allTime,
      project: 'lyhad',
      entryId: '1',
      item:"65",
      sourceType: "105",
      sourceValue: this.data.indexList[index].code
    }
    if (timeStop) { data.timeStop = timeStop }
    http.lhxRequest("api_addUserPlayLog", data).then(res => {
      if (res.code === 10000000) {
        console.log('添加播放记录');
      }
    })
  },
  fnPlayVideo(e) {
    let STOP_TIME = this.data.log.STOP_TIME;
    if (STOP_TIME) {
      //有这个就执行
      this.addHistory(this.data.log.code, this.data.log.allTime, this.data.log._index, STOP_TIME);
    }
    let _index = e.currentTarget.dataset.id;
    let code = e.currentTarget.dataset.code;
    let freeFlag = e.currentTarget.dataset.freeflag;
    let indexList = this.data.indexList;
    let img = e.currentTarget.dataset.img;
    let totalNum = e.currentTarget.dataset.num;
    let name = e.currentTarget.dataset.name;
    let data = {
      albumCode: code,
      selectFlag: 0,
      project: this.data.query.project,
      px: this.data.query.px,
      pagesize: this.data.query.pagesize,
    }

    for (let i in indexList) {
      indexList[i].flagShow = false;
    }
    this.setData({
      indexList: indexList,
      _index: _index,
      code: code,
      freeFlag: freeFlag,
      index: 0,
      ['log.STOP_TIME']: null
    })
    http.lhxRequest("api_getAlbumResList", data).then(res => {
      if (res.code === 10000000) {
        if (res.pb) {
          let code = [];
          for (let i in res.pb.dataList) {
            code.push(res.pb.dataList[i].code)
          }
          this.setData({
            codeArr: code // 专辑code集合
          })
          let record = {
            img: img,//展示封面图
            name: name,//剧名
            code: res.pb.dataList[this.data.index].code,//专辑code
            freeFlag: freeFlag,//是否免费
            totalNum: totalNum,//总共几集
          };

          if (!wx.getStorageSync('openid')) {
            app.recordHistory(record);
          } else {
            let code = res.pb.dataList[this.data.index].code;
            let aTime = res.pb.dataList[this.data.index].allTime;
            this.setData({
              ['log.code']: code,
              ['log.allTime']: aTime,
              ['log._index']: _index
              
            })
            this.addHistory(code, aTime, _index);
          }
          this.fnSeriesPlay(code, _index)
        }
      }
    })
  },
  // 连续播放
  fnSeriesPlay(code, index) {
    // 默认播放第一个
    let idx = this.data.index;
    this.fnGetPlayUrl(code[idx], index)
  },
  // 视频拨到末尾触发
  videoTimeEnded: function (res) {
    let that = this;
    let idx = that.data.index;
    let code = that.data.codeArr;
    let STOP_TIME = this.data.log.STOP_TIME;
    if (STOP_TIME) {
      //有这个就执行
      this.addHistory(this.data.log.code, this.data.log.allTime, this.data.log._index, STOP_TIME);
    }
    // 代表最后一集
    if (idx > code.length - 1) {
      let videoContextPrev = wx.createVideoContext('myVideo' + this.data._index);
      videoContextPrev.stop();
      that.setData({
        _index: null
      })
    } else {
      that.fnGetPlayUrl(code[idx])
    }
  },
  fnGetPlayUrl(code, index) {
    console.log(index,"我的COde")
    let data = {
      userId: this.data.query.userId,
      resCode: code,
      px: this.data.query.px,
      item: 65
    }
    http.lhxRequest("api_getPlayUrl", data).then(res => {
      if (res.code === 10000000) {
        let indexList = this.data.indexList;
        for (let i in indexList) {
          indexList[i].playurl = "";
          console.log(res.playres.playurl, 10086)
          if (indexList[i].code == this.data.code) {
            indexList[i].playurl = res.playres.playurl
            console.log(indexList[i].playurl,10086)
          }
        }
        this.setData({
          indexList: indexList,
        })

        let videoContext = wx.createVideoContext('myVideo' + index);
        videoContext.play();

        this.setData({
          index: this.data.index + 1
        })
      }
    })
  },
  // 不是vip并且不是免费的试看三分钟
  videoTimeupdate: function (e) {
    if (!this.data_index) {
      this.setData({
        ['log.STOP_TIME']: e.detail.currentTime,//停止播放得时间
      })
    }
    console.log(this.data.log.START_TIME, this.data.log.STOP_TIME)
    if (!this.data.isVIP && this.data.freeFlag == 0) {
      if (e.detail.currentTime >= 180) {
        let videoContextPrev = wx.createVideoContext('myVideo' + this.data._index);
        videoContextPrev.stop();
        this.data.indexList[this.data._index].flagShow = true;
        this.setData({
          indexList: this.data.indexList,
        })
      }
    }
  },
  // 分享
  onShareAppMessage: function (res) {
    let imgUrl = app.globalData.baseUrlImg;
    let item = res.target.dataset.item;
    if (res.from === "button") {
      return {
        title: item.name,
        imageUrl: imgUrl + item.img,
        path: "/pages/album_details/album_details?code=" + item.code
      }
    }
  },
  // 查看
  fnSeeDetails(e) {
    let code = e.currentTarget.dataset.code;
    wx.navigateTo({
      url: "/pages/album_details/album_details?code=" + code,
    })
  },
  // 日志
  uniteLog(data) {
    http.lhxRequest("api_log", data).then(res => {
      if (res.code === 10000000) {
        console.log("日志")
      }
    })
  },
})